package com.heima.admin.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.heima.admin.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
@Order(0)
public class AuthorizeFilter implements GlobalFilter {
    List<String> urlList = Arrays.asList(
            "/v2/api-docs",
            "/login/in"
    );

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求和响应
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //**** 2. 判断当前请求路径是否放行
        String reqUrl = request.getURI().getPath();
        for (String url : urlList){
            if (reqUrl.endsWith(url)) {
                return chain.filter(exchange);
            }
        }

        //获取token
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)) {
            //不存在,拦截并提示错误信息401
            HashMap<String, Object> map = new HashMap<>();
            map.put("host", request.getRemoteAddress().getHostName());
            map.put("code", HttpStatus.UNAUTHORIZED.value());
            map.put("errorMessage", "需要登录");
            return writeMessage(exchange, map);
        }
        try {
            //存在则校验token,判断令牌是否正确
            Claims claims = AppJwtUtil.getClaimsBody(token);
            //  -1：有效，0：有效，1：过期，2：过期
            int i = AppJwtUtil.verifyToken(claims);
            if (i > 0) {
                //令牌无效,拦截并提示错误信息401
                HashMap<String, Object> map = new HashMap<>();
                map.put("host", request.getRemoteAddress().getHostName());
                map.put("code", HttpStatus.UNAUTHORIZED.value());
                map.put("errorMessage", "认证失败,请重新登录");
                return writeMessage(exchange, map);
            }
            //解析JWT令牌信息
            Integer id = claims.get("id", Integer.class);
            log.info("header token id:{}, URL:{}", id, request.getURI().getPath());

            //***4 将令牌信息传递到对应的微服务
            ServerHttpRequest serverHttpRequest = request.mutate().
                    headers(httpHeaders -> {
                        httpHeaders.add("userId", String.valueOf(id));
                    }).build();
            exchange.mutate().request(serverHttpRequest).build();
        } catch (Exception e) {
            log.error("verifyToken is fail..:{}", e);
            Map<String, Object> map = new HashMap<>();
            map.put("host", request.getRemoteAddress().getHostName());
            map.put("code", HttpStatus.UNAUTHORIZED.value());
            map.put("errorMessage", "认证失效，请重新登录");
            return writeMessage(exchange, map);
        }
        //返回结果
        return chain.filter(exchange);
    }

    /**
     * 返回错误提示信息
     *
     * @param exchange
     * @param resultMap 响应结果
     * @return
     */
    private Mono<Void> writeMessage(ServerWebExchange exchange, Map<String, Object> resultMap) {
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //设置状态码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //response.setStatusCode(HttpStatus.OK);
        //设置返回类型
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        //设置返回数据
        DataBuffer buffer = response.bufferFactory().wrap(JSON.toJSONBytes(resultMap));
        //响应数据回浏览器
        return response.writeWith(Flux.just(buffer));
    }
}
